package com.hzw.saas.web.app.msg.controller;


import java.util.List;
import java.util.Objects;
import javax.annotation.Resource;
import javax.validation.Valid;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hzw.saas.api.group.IGroupMemberService;
import com.hzw.saas.api.msg.IMsgService;
import com.hzw.saas.api.msg.bo.MsgBo;
import com.hzw.saas.api.msg.bo.MsgCountBo;
import com.hzw.saas.api.msg.enums.MsgRead;
import com.hzw.saas.api.msg.enums.MsgType;
import com.hzw.saas.api.msg.query.MsgGroupQuery;
import com.hzw.saas.api.msg.query.MsgSearchQuery;
import com.hzw.saas.api.msg.query.MsgSystemQuery;
import com.hzw.saas.api.msg.query.MsgUserQuery;
import com.hzw.saas.common.config.annotation.SysLog;
import com.hzw.saas.common.config.util.AssertUtil;
import com.hzw.saas.common.config.util.PageParam;
import com.hzw.saas.common.security.utils.SecurityUtils;
import com.hzw.saas.service.msg.tool.MsgContentParser;
import com.hzw.saas.web.app.msg.param.MsgReadParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiOperationSort;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;

/**
 * <p>
 * 消息表 前端控制器
 * </p>
 *
 * @author sonam
 * @since 2020-12-22
 */
@RestController
@RequestMapping("/user")
@AllArgsConstructor
@Api(tags = "用户中心/用户消息")
public class UserMsgController {
    @Resource(name = "msgServiceImpl")
    private IMsgService userMsgService;
    @Resource(name = "groupMemberServiceImpl")
    private IGroupMemberService groupMemberService;
    private final MsgContentParser msgContentParser;

    @GetMapping("/msg/count")
    @ApiOperation(value = "获取当前用户未读消息数量", notes = "获取当前用户消息数量")
    @ApiOperationSort(1)
    public ResponseEntity<MsgCountBo> getMsgCount() {
        String userId = SecurityUtils.getUser().getUserId();
        return ResponseEntity.ok(userMsgService.getMsgCountByUserId(userId));
    }

    @GetMapping("/msg")
    @ApiOperation(value = "根据消息类型获取消息", notes = "1：系统消息，2：群主消息，3：个人消息")
    @ApiOperationSort(2)
    public ResponseEntity<IPage<MsgBo>> getAllSystemMsg(PageParam pageParam,@RequestParam Integer type) {
        String userId = SecurityUtils.getUser().getUserId();

        MsgType msgType = MsgType.instance(type);
        AssertUtil.assertThrow("获取消息失败，不存在的消息类型", Objects.isNull(msgType));

        MsgSearchQuery msgSearchQuery = new MsgSearchQuery().setMsgRead(null).setMsgType(msgType).setUserId(userId);
        IPage<MsgBo> msgList = userMsgService.findAllMsgByUserIdAndTypeAndRead(pageParam, msgSearchQuery);
        /** 解析消息文本*/
        msgContentParser.parser(msgList.getRecords());

        return ResponseEntity.ok(msgList);
    }

    @SysLog(operation = "设置消息已读/未读")
    @PutMapping("/msg/read")
    @ApiOperation(value = "设置消息已读/未读", notes = "设置消息状态为已读/未读")
    @ApiOperationSort(4)
    public ResponseEntity<String> setMsgRead(@Valid @RequestBody MsgReadParam msgReadParam) {
        MsgRead userMsgRead = MsgRead.instance(msgReadParam.getRead());
        AssertUtil.assertThrow("可读或已读状态设置错误", Objects.isNull(userMsgRead));
        String userId = SecurityUtils.getUser().getUserId();
        userMsgService.setMsgRead(msgReadParam.getMsgId(), userId, userMsgRead);
        switch (userMsgRead) {
            case UNREAD:
                return ResponseEntity.ok("设置消息未读");
            case READ:
                return ResponseEntity.ok("设置消息已读");
        }
        return null;
    }

    @SysLog(operation = "设置消息全部已读")
    @PutMapping("/msg/all/read")
    @ApiOperation(value = "设置消息全部已读", notes = "设置消息全部已读")
    @ApiOperationSort(5)
    public ResponseEntity<String> setMsgAllRead() {
        userMsgService.setMsgAllRead(SecurityUtils.getUser().getUserId());
        return ResponseEntity.ok("设置消息全部已读");
    }

    @SysLog(operation = "清空本人所有消息（测试）")
    @DeleteMapping("/msg/")
    @ApiOperation(value = "清空本人所有消息（测试）", notes = "根据类型清空所有消息")
    @ApiOperationSort(6)
    public ResponseEntity<Void> clearMsgByType(@ApiParam(value = "消息类型: 1:系统消息|2:群组消息|3:个人消息|0:全部消息")
                                                   @RequestParam Integer msgType) {
        // TODO 消息存在业务信息，清空需要判断
        List<String> msgIds = userMsgService.getAllMsgIdList(SecurityUtils.getUser().getUserId(), null);
        userMsgService.deleteMsgByMsgIdsAndUserId(msgIds, SecurityUtils.getUser().getUserId());
        return ResponseEntity.ok().build();
    }

    @GetMapping("/msg/{msgId}")
    @ApiOperation(value = "通过id获取消息", notes = "通过id获取消息(测试)")
    @ApiOperationSort(7)
    public ResponseEntity<MsgBo> getAllMsg(@PathVariable String msgId) {
        return ResponseEntity.ok(userMsgService.getMsgById(msgId));
    }

    @SysLog(operation = "系统发送一条消息")
    @PutMapping("/msg/system")
    @ApiOperation(value = "系统发送一条消息（测试用）", notes = "系统发送一条消息（测试用）")
    @ApiOperationSort(8)
    public void addMsg(@Valid @RequestBody MsgSystemQuery msgParam) {
        userMsgService.addMsg(msgParam);
    }

    @SysLog(operation = "群组发一条消息")
    @PutMapping("/msg/group")
    @ApiOperation(value = "群组发一条消息（测试用）", notes = "群组发一条消息（测试用）")
    @ApiOperationSort(9)
    public void addMsg(@Valid @RequestBody MsgGroupQuery msgParam) {
        userMsgService.addMsg(msgParam);
    }

    @SysLog(operation = "用户发送一条消息给指定用户")
    @PutMapping("/msg")
    @ApiOperation(value = "用户发送一条消息给指定用户（测试用）", notes = "发送一条消息给指定用户")
    @ApiOperationSort(10)
    public void addMsg(@Valid @RequestBody MsgUserQuery msgParam) {
        if (StringUtils.isBlank(msgParam.getFrom())) {
            msgParam.setFrom(SecurityUtils.getUser().getUserId());
        }
        userMsgService.addMsg(msgParam);
    }

}
